﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerControl : MonoBehaviour
{
    [Header("角色信息")]
    public SpriteRenderer spriteRenderer;
    public Sprite idleSprite;
    public Sprite tileSprite;
    public Sprite victorySprite;
    //碰撞器
    private BoxCollider2D boxCollider2D;
    private CircleCollider2D circleCollider2D;
    private CapsuleCollider2D capsuleCollider2D;
    private Rigidbody2D rigi;
    //点坐标
    public GameObject[] points;
    private float distance;
    /// <summary>
    /// 被选中的点
    /// </summary>
    private GameObject point;
    private float addForce = 3;

    public LineRenderer line;
    private Vector2 linePoint_0;
    private Vector2 linePoint_1;
    /// <summary>
    /// 角色中心到y轴顶端的偏差值
    /// </summary>
    private readonly float offset_Y = 0.5f;

    /// <summary>
    /// 松开鼠标左键时，给物体额外的力
    /// </summary>
    public float AddForce { get => addForce; }

    private void Awake()
    {
        boxCollider2D = GetComponent<BoxCollider2D>();
        circleCollider2D = GetComponent<CircleCollider2D>();
        capsuleCollider2D = GetComponent<CapsuleCollider2D>();
        rigi = GetComponent<Rigidbody2D>();
    }

    private void Start()
    {
        boxCollider2D.enabled = false;
        circleCollider2D.enabled = true;
        //points = GameObject.FindGameObjectsWithTag("Point");
        distance = Mathf.Infinity;
    }

    /// <summary>
    /// 当人物角色被激活时，更新玩家皮肤
    /// </summary>
    private void OnEnable()
    {
        spriteRenderer.sprite = idleSprite;
        //Debug.Log("更改皮肤");
    }

    private void Update()
    {
        if (GameControl.instance.InGame)
        {
            OnMouseDown();
            OnMouseUp();
            DrawnLine();

            if (Mathf.Abs(transform.rotation.z) > 90)
            {
                if (rigi.velocity.x > 0f)
                {
                    spriteRenderer.flipX = true;
                }
                else if (rigi.velocity.x < 0f)
                {
                    spriteRenderer.flipX = false;
                }
            }
            else
            {
                if (rigi.velocity.x > 0f)
                {
                    spriteRenderer.flipX = false;
                }
                else if (rigi.velocity.x < 0f)
                {
                    spriteRenderer.flipX = true;
                }
            }
        }

        rigi.velocity = Vector2.ClampMagnitude(rigi.velocity, 45f);
        
        
    }

    /// <summary>
    /// 得到距角色最近的节点
    /// </summary>
    /// <returns></returns>
    public GameObject FindPoint()
    {
        if (points.Length == 0)
        {
            return null;
        }
        GameObject temPoint = null;
        for (int i = 0; i < points.Length; i++)
        {
            float temDis = Vector2.Distance(points[i].transform.position, transform.position);
            if (distance >= temDis)
            {
                distance = temDis;
                temPoint = points[i];
            }
        }
        linePoint_1 = temPoint.transform.position;
        line.SetPosition(1, linePoint_1);

        distance = Mathf.Infinity;
        return temPoint;

    }

    /// <summary>
    /// 到达终点,角色呈胜利姿态
    /// </summary>
    /// <param name="collision"></param>
    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.tag.Equals("Ending"))
        {
            //Debug.LogError(User.instance.levelSkinList.Count);

            line.enabled = false;
            StartCoroutine(GameControl.instance.GameWinAction());

        }
    }

    /// <summary>
    /// 按下鼠标左键，角色呈荡绳状态
    /// </summary>
    public void OnMouseDown()
    {
        if (Input.GetMouseButtonDown(0))
        {
            //Handheld.Vibrate();
            point = FindPoint();
            if (point != null)
            {
                transform.up = (point.transform.position - transform.position).normalized;
                point.transform.GetComponent<HingeJoint2D>().connectedBody = rigi;
                //point.transform.GetComponent<SpringJoint2D>().connectedBody = rigi;
                spriteRenderer.sprite = tileSprite;
                //boxCollider2D.enabled = true;
                //capsuleCollider2D.enabled = true;
                //circleCollider2D.enabled = false;
                line.enabled = true;
            }
            //Debug.Log("Down");
        }
    }

    /// <summary>
    /// 松开鼠标，角色成球状
    /// </summary>
    public void OnMouseUp()
    {
        if (Input.GetMouseButtonUp(0) || !GameControl.instance.InGame  /*&& point != null*/)
        {
            if (point)
            {
                transform.GetComponent<Rigidbody2D>().velocity += (Vector2)(point.transform.position - transform.position).normalized * AddForce;
                //rigi.AddForce(Vector2.up * AddForce, ForceMode2D.Impulse);

                point.GetComponent<HingeJoint2D>().connectedBody = null;
                //point.GetComponent<SpringJoint2D>().connectedBody = null;
                
            }

            spriteRenderer.sprite = idleSprite;
            //boxCollider2D.enabled = false;
            //capsuleCollider2D.enabled = false ;
            //circleCollider2D.enabled = true;

            line.enabled = false;
            //Debug.Log("up");
        }
    }

    /// <summary>
    /// 画线函数
    /// </summary>
    public void DrawnLine()
    {
        linePoint_0 = transform.position + transform.up * offset_Y;
        line.SetPosition(0, linePoint_0);
    }









}
